package com.cl.springbootfiles.schedule;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;

@Component
@EnableScheduling
public class FileCleanSchedule {
    private static final Logger log = LoggerFactory.getLogger(FileCleanSchedule.class);
    private static final ZoneId zoneId = ZoneId.systemDefault();
    @Value("${save-path}")
    private String savePath;
    @Value("${clean-days-before}")
    private long cleanDaysBefore;

    public FileCleanSchedule() {
    }

    @Scheduled(cron = "0 0 1 * * ?")
    public void fileClean() {
        if (cleanDaysBefore <= 0) {
            return;
        }
        log.info("警告！开始清理超期文件");
        File[] files = new File(this.savePath)
                .listFiles((dir, name) -> LocalDateTime.ofInstant(Instant.ofEpochMilli((new File(dir, name)).lastModified()), zoneId)
                        .plusDays(this.cleanDaysBefore)
                        .isBefore(LocalDateTime.now(zoneId))
                );
        if (null != files && files.length != 0) {
            ArrayList<String> deletedFileName = new ArrayList<>(files.length);
            Arrays.stream(files).forEach((file) -> {
                String fileName = file.getName();
                log.info("文件：{}已超过{}天，文件已被删除", fileName, this.cleanDaysBefore);
                if (FileUtils.deleteQuietly(file)) {
                    deletedFileName.add(fileName);
                }
            });
            log.info("本次共删除文件{}个", deletedFileName.size());
        } else {
            log.info("未发现超过{}天的文件，本次未删除任何文件", this.cleanDaysBefore);
        }
    }
}